<template>
    <el-form :model="book" label-position="right" label-width="auto">
        <el-row :gutter="10">
            <el-col :span="12">
                <el-form-item label="书名" prop="name">
                    <el-input v-model="book.name" placeholder="请输入书名" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="作者" prop="author">
                    <el-input v-model="book.author" placeholder="请输入作者" clearable/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="10">
            <el-col :span="12">
                <el-form-item label="出版日期" prop="date">
                    <el-input type="date" v-model="book.date" placeholder="请输入日期" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="出版社" prop="press">
                    <el-input v-model="book.press" placeholder="请输入出版社" clearable/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="10">
            <el-col :span="12">
                <el-form-item label="价格" prop="price">
                    <el-input v-model="book.price" placeholder="请输入价格" type="number" clearable/>
                </el-form-item>
            </el-col>
        </el-row>

    </el-form>

    <el-row>
        <el-col>
            <div style="text-align: center;">
                <el-button type="primary" @click="doSave">保存</el-button>
                <el-button @click="doCancel">取消</el-button>
            </div>
        </el-col>
    </el-row>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import {ElMessage} from "element-plus";
import axios from 'axios';

//---------------------------- 自定义组件事件 -----------------------------
const emits = defineEmits(["closeDialog", "flushPage"]);

const book = ref({
    name: "",
    author: "",
    date: "",
    press: "",
    price: 0
})

// 取消
const doCancel = () => {
    // 触发事件：关闭 dialog
    emits("closeDialog");
}

// 新增
const doSave = async () => {
    const {data} = await axios.post('/api/book', book.value);
    console.log(data);
    if (data > 0) {
        emits("flushPage");				// 触发事件： 刷新页面
        emits("closeDialog");			// 触发事件：关闭 dialog
        ElMessage.success("操作成功！");
    } else {
        ElMessage.error("操作失败！");
    }
}
</script>